package com.smartcommunity.elasticsearch.accesscontrol;

import com.smartcommunity.elasticsearch.accesscontrol.req.AccesscontrolEsReq;
import com.smartcommunity.es.common.EsIndex;
import com.smartcommunity.es.common.EsRestUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName FaceEsApi
 * @Author lilun
 * @Description TODO
 * @Date 2019/12/27 14:01
 * @Version 1.0
 */

@Component
@Slf4j
public class AccesscontrolEsApi {

    @Autowired
    private EsRestUtils eSRestUtils;

    public List<Map<String, Object>> searchRecentlyCaptureAccesscontrol(AccesscontrolEsReq accesscontrolEsReq) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (StringUtils.isNotBlank(accesscontrolEsReq.getVillageCode())) {
            boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("villageCode", accesscontrolEsReq.getVillageCode()));
        }
        boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("deviceId", accesscontrolEsReq.getDeviceId()));
        SortBuilder sortBuilder = null;
        if (StringUtils.isNotBlank(accesscontrolEsReq.getSortField())) {
            sortBuilder = SortBuilders.fieldSort(accesscontrolEsReq.getSortField());
            switch (accesscontrolEsReq.getSortMode()) {
                case "desc":
                    sortBuilder.order(SortOrder.DESC);
                    break;
                case "asc":
                    sortBuilder.order(SortOrder.ASC);
                    break;
                default:
                    sortBuilder.order(SortOrder.DESC);
            }
        }
        try {
            return eSRestUtils.page(new String[]{EsIndex.ACCESSRECORD_ALIAS}, boolQueryBuilder, accesscontrolEsReq.getFields(), accesscontrolEsReq.getPageNum(), accesscontrolEsReq.getPageSize(), sortBuilder);
        } catch (Exception e) {
            log.error("es  查询错误", e);
        }
        return new ArrayList<>();
    }

    public Long getAccessControllerCopunt() {
        try {
            return eSRestUtils.getTotalRecords(new String[]{EsIndex.ACCESSRECORD_ALIAS}, QueryBuilders.matchAllQuery());
        } catch (IOException e) {
            log.error("查询门禁数据接入数据总量失败,e:", e);
            return 0L;
        }
    }
}
